//HttpUtils.cpp

#include "httputils.h"
#include <QDebug>
#include <QNetworkReply>
#include <QJsonDocument>


HttpUtils::HttpUtils(QObject *parent) : QObject(parent)
{
    manager = new QNetworkAccessManager(this);
    QObject::connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));

}


void HttpUtils::replyFinished(QNetworkReply* reply){
    QString result =reply->readAll();
    emit replySignal(result);
}

void HttpUtils::getApi(QString url,QString paramName,QString param,int page=0, int pageSize=0  )
{

    QUrlQuery query;
    if(page==0&&pageSize==0){

        query.addQueryItem(paramName, param); // 添加查询参数userId和其值
    }else{
        query.addQueryItem("page", QString::number(page)); // 添加查询参数page和其值
        query.addQueryItem("pageSize", QString::number(pageSize)); // 添加查询参数pageSize和其值
        query.addQueryItem(paramName, param); // 添加查询参数userId和其值
    }

    QNetworkRequest request;
    // 将查询字符串设置为请求的URL
    request.setUrl(BASE_URL+url+"?"+query.toString());
    qDebug()<< query.toString();
    qDebug()<< url;
    qDebug()<< request.url();

    manager->get(request);
}

void HttpUtils::postApi(QString url, QVariantMap data)
{
    QJsonObject jsonObject;
    for (const auto &entry : data.toStdMap()) {
        jsonObject[entry.first] = entry.second.toString(); // 将数据转换为JSON对象
    }
    QJsonDocument jsonDoc(jsonObject);
    QNetworkRequest request;
    request.setUrl(QUrl(BASE_URL + url));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); // 设置请求头为JSON格式
    manager->post(request, jsonDoc.toJson()); // 发送POST请求，将JSON对象作为请求体发送给后端
}





HttpUtils::~HttpUtils(){
    delete manager;
}
